<?php
/* ******************************
 * INVOICE aJax actions
 * ******************************
 */

set_time_limit(0);

include('../../includes/classes/core.php');
include('../../includes/classes/invoice.class.php');

$service_url	= 'https://www.revenue.mof.ge/ntosservice/ntosservice.asmx?WSDL';
$action			= $_REQUEST['act'];
$client_id		= $_REQUEST['client_id'];
$error			= '';
$data			= '';
$properties 	= GetCompanyProperties();
$c_date 		=  "2015-".$_REQUEST['month'];


$invoice	= new invoice($service_url, $properties['su'], $properties['sp'], $properties['rs_user_id'], $properties['un_id']);

switch ($action) {
	case 'create_invoice':
	$warehouse_ids		= json_decode( '['.$_REQUEST['wareHouseID'].']' );
	//$client_id='174';
	$invoice->set_invoice_id(0);
		$buyer_un_id  =   GetClientUnId($client_id);
	if($buyer_un_id > 10) 
	{ 
		$result      = $invoice->create_invoice( $c_date, $buyer_un_id);
		if( $result['results'] ){
			$error = 'ანგარიშფაქტურა წარმატებით გაიგზავნა!';

			SaveInvoiceId($result['invoice_id'], $warehouse_ids);
			$invoice->set_invoice_id($result['invoice_id']);
			$array = AddServicesToInvoice($result['invoice_id']);

			for ($i = 0; $i < count($array); $i++) {
				$result =  $invoice->add_services_in_invoice($array[$i]['service'], $array[$i]['quantity'], $array[$i]['price']);
			}

			$invoice->send_invoice();
			//$invoice->get_invoice();
			$invoice->get_invoice();

		}else{
			$error = 'ანგარიშფაქტურა არ გაიგზავნა!';
		}		
	}else {
	    $error = 'საიდენთიპიკაციო არაა შეყვანილი!';
	}

		break;
	case 'rs_sinc':
	    $error = $invoice->rs_sinc();
		break;
	case 'save_client':
		$arr = $invoice->check_client($_REQUEST[ri]);
		mysql_query("UPDATE `client` SET
		             `rs_un_id`='$arr->get_un_id_from_tinResult'
		             WHERE (`rs_id`='$_REQUEST[ri]')");
        $data[mesage]=$arr->name;             
	   break;
	default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode( $data );


/* ******************************
 *	INVOICE Functions
 * ******************************
 */

function GetCompanyProperties()
{
	$res = mysql_fetch_assoc(mysql_query("SELECT 	`su`,
    											 	`sp`,
													`rs_user_id`,
													`un_id`
									      FROM 		`company_properties`"));
	return $res;
}

function GetClientUnId($client_id){
	$res = mysql_fetch_assoc(mysql_query("
											SELECT 	`client`.`rs_un_id` AS `id`
											FROM 	`client`
											WHERE 	`client`.`id` = '$client_id'"));
	return $res['id'];

}

function SaveInvoiceId($invoice_id, $warehouse_ids){
	foreach ($warehouse_ids as $warehouse_id){
		$res = mysql_fetch_array( mysql_query("	SELECT		`warehouse`.`a_letter_id` as `a_letter_id`,
															`warehouse`.`d_letter_id` as `d_letter_id`
												FROM		`warehouse`
												WHERE		`warehouse`.`id` = '$warehouse_id'"));
		if($res['a_letter_id'] != ''){
			$a_letter_id = $res['a_letter_id'];
			mysql_query("	UPDATE 	`a_letter`
							SET		`a_letter`.`invoice_id` = '$invoice_id'
							WHERE	`a_letter`.`id` = '$a_letter_id' ");
		}else if($res['d_letter_id'] != ''){
			$d_letter_id = $res['d_letter_id'];
			mysql_query("	UPDATE 	`d_letter`
							SET		`d_letter`.`invoice_id` = '$invoice_id'
							WHERE	`d_letter`.`id` = '$d_letter_id' ");
		}
	}
}

function AddServicesToInvoice($invoice_id) {

	$result = mysql_query("
                    SELECT	CASE	WHEN `cartridge_parts_type`.`id` = 2 THEN	CONCAT(production.`name`, ' ', ' - დამუხტვა')
                    				ELSE	CONCAT(production.`name`,' - ', `cartridge_parts_type`.`name`, 'ს შეცვლა')
                    				END AS service,
                    				COUNT(*) AS quantity,
                    				sum(IF(warehouse_detail.type=2 AND b_letter_details.part_type_id=2,0.00,b_letter_details.price)) as price
                    FROM    a_letter
                    JOIN    b_letter_details ON b_letter_details.a_letter_id=a_letter.id AND `b_letter_details`.`price` > 0
                    JOIN 		warehouse_detail ON `warehouse_detail`.`id` = `b_letter_details`.`warehouse_detail_id` AND warehouse_detail.actived=1
                    JOIN    production ON warehouse_detail.prod_id = production.id
                    JOIN 		cartridge_parts_type ON `b_letter_details`.`part_type_id` = `cartridge_parts_type`.`id`
                    WHERE   a_letter.invoice_id = '$invoice_id'	
	                GROUP BY 	service 
                    HAVING price > 0
                    UNION ALL
                    SELECT		CONCAT(production.`name`,' - ',`printer_parts_type`.`name`) AS service,                					
                    					COUNT(*) AS quantity,
                    					SUM(`e_letter_details`.`price`) AS price
                    FROM  	d_letter
                    JOIN 		e_letter_details ON e_letter_details.d_letter_id=d_letter.id AND `e_letter_details`.`price` > 0
                    JOIN 		warehouse_detail ON `warehouse_detail`.`id` = `e_letter_details`.`warehouse_detail_id` AND warehouse_detail.actived=1 AND warehouse_detail.type !=2
                    JOIN  	production ON warehouse_detail.prod_id = production.id
                    JOIN 		printer_parts_type ON `e_letter_details`.`part_type_id` = `printer_parts_type`.`id`
                    WHERE 	d_letter.invoice_id = '$invoice_id' 
	                GROUP BY 	service 
                    HAVING price > 0   
						");
	$array = array();
	while ($row = mysql_fetch_assoc($result)) {
		$array[] = array(
						"service" 	=> $row['service'],
						"quantity" 	=> $row['quantity'],
						"price"		=> $row['price']
						);
	}

	return $array;
}
?>